﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;

namespace SurveyTrackerV2.Admin
{
    public partial class AddEmailsFromFile : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                SurveyTrackerV2DB db  = new SurveyTrackerV2DB();
                var emailLists = from el in db.Lists
                                 where el.ListStatus == 1
                                 select el;
                
                cblEmailLists.DataSource = emailLists.ToList<List>();
                cblEmailLists.DataValueField = "ListId";
                cblEmailLists.DataTextField = "ListName";
                
                cblEmailLists.DataBind(); 
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            List<string> emailAddresses = GetEmailAddressesFromFile();
            List<int> lstListId = GetListIDs();
            AddEmailsToDB(emailAddresses, lstListId);
        }

        /// <summary>
        /// Adds the emails to DB.
        /// </summary>
        /// <param name="emailAddresses">The email addresses.</param>
        /// <param name="lstListId">The LST list id.</param>
        private void AddEmailsToDB(List<string> emailAddresses, List<int> lstListId)
        {
      
            try
            {
                foreach (var item in emailAddresses)
                {
                    Email e = new Email();
                
                    if(!EmailExists(item))
                    {
                        e.EmailStatus = 1;
                        e.EmailAddress = item;
                        e.Save();
                    }
                    else
                    {
                        SurveyTrackerV2DB db = new SurveyTrackerV2DB();
                        var email = from em in db.Emails
                                    where em.EmailAddress == item
                                    select em;
                        
                        e = email.First();
                    }

                    foreach (var listItem in lstListId)
                    {
                           
                        EmailList el = new EmailList();
                        int listItemId = int.Parse(listItem.ToString());
                        
                        if(!EmailListItemExists(e.EmailId,listItemId))
                        {
                            el.ListId = listItemId;
                            el.EmailId = e.EmailId;
                            el.EmailListStatus = 1;
                            el.Save();
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        

        }

        /// <summary>
        /// Emails the list item exists.
        /// </summary>
        /// <param name="emailid">The emailid.</param>
        /// <param name="listItemId">The list item id.</param>
        /// <returns></returns>
        private bool EmailListItemExists(int emailid, int listItemId)
        {
            bool doesEmailListItemExists = false;
            
            SurveyTrackerV2DB db = new SurveyTrackerV2DB();
            var emails =    from ele in db.EmailLists
                            where ele.ListId == listItemId && ele.EmailId == emailid
                            select ele;

            if (emails.Count() > 0)
            {
                doesEmailListItemExists = true;
            }

            return doesEmailListItemExists;
        }

        /// <summary>
        /// Emails the exists.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <returns></returns>
        private bool EmailExists(string item)
        {
            bool doesEmailAddress = false;
            
            SurveyTrackerV2DB db = new SurveyTrackerV2DB();
            var email = from e in db.Emails
                        where e.EmailAddress == item
                        select e;
                        
            if(email.Count() > 0)
            {
                doesEmailAddress = true;
            }
            
            return doesEmailAddress;
        }


        /// <summary>
        /// Gets the list I ds.
        /// </summary>
        /// <returns></returns>
        private List<int> GetListIDs()
        {
            List<int> lstListIds = new List<int>();
           
            foreach (ListItem item in cblEmailLists.Items)
            {
                if (item.Selected)
                {
                    lstListIds.Add(int.Parse(item.Value));
                }
            }
            
            return lstListIds;
        }

        /// <summary>
        /// Gets the email addresses from file.
        /// </summary>
        /// <returns></returns>
        private List<string> GetEmailAddressesFromFile()
        {
            List<string> lstEmailAddresses = new List<string>();
            
            string strEmailAddress = string.Empty;
            StreamReader sr = new StreamReader(fuCSVFile.PostedFile.InputStream);

            try
            {
                string header = sr.ReadLine();
                while (!sr.EndOfStream)
                {
                    lstEmailAddresses.Add(sr.ReadLine());
                }
            }
            catch (Exception)
            {
                throw new FileLoadException("File is empty");
            }
            
            return lstEmailAddresses;            
        }
    }
}
